package com.zilue.hfqueue.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ZD on 2017/6/1.
 */
public class ChannelExecutorServer {
    private static final int MAX=20;
    private static final ExecutorService executor= Executors.newFixedThreadPool(MAX);

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8092));
        System.out.println("listening port 8092!");

        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            executor.execute(new RequestHandler(socketChannel));
        }
//        Selector selector = Selector.open();
//        serverSocketChannel.configureBlocking(false);
//        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//        while (true) {
//            int readChannels = selector.select();
//            if (readChannels==0)
//                continue;
//            Set<SelectionKey> selectionKeys = selector.selectedKeys();
//            Iterator<SelectionKey> iterator = selectionKeys.iterator();
//            while (iterator.hasNext()){
//                SelectionKey key = iterator.next();
//                if(key.isAcceptable()) {
//                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
////                    new Thread(new RequestHandler(channel.accept())).start();
//                    executor.execute(new RequestHandler(channel.accept()));
//                } else if (key.isConnectable()) {
//                    // a connection was established with a remote server.
//                } else if (key.isReadable()) {
//                    // a channel is ready for reading
//                } else if (key.isWritable()) {
//                    // a channel is ready for writing
//                }
//                iterator.remove();
//            }
//        }
    }

}
